package com.ruicar.afs.cloud.gateway.handler.loginprocess;

import cn.hutool.core.util.StrUtil;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.exception.ValidateCodeException;
import com.ruicar.afs.cloud.common.core.security.feign.Oauth2OperationService;
import com.ruicar.afs.cloud.common.core.util.ClientTypeUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
@Slf4j
@Component
@AllArgsConstructor
public class DefaultLoginProcess implements LoginProcess{
    private final Oauth2OperationService oauth2OperationService;
    private final RedisTemplate redisTemplate;
    @Override
    public List<ClientTypeUtil.ClientTypeEnum> supportClientType() {
        return Arrays.asList(ClientTypeUtil.ClientTypeEnum.PC);
    }

    @Override
    public void checkHeader(Map<String, String> headers) {

    }


    @Override
    public Oauth2OperationService getOauthClient() {
        return oauth2OperationService;
    }

    @Override
    public void checkBody(Map<String, String> bodyParams) {
        checkCode(bodyParams.get("code"), bodyParams.get("captchaKey"));
    }

    /**
     * 检查code
     *
     * @throws ValidateCodeException 校验异常
     */
    private void checkCode(String code, String captchaKey){

        if (StrUtil.isBlank(code)) {
            throw new AfsBaseException("验证码不能为空");
        }

        String key = CommonConstants.DEFAULT_CODE_KEY + captchaKey;
        if (!redisTemplate.hasKey(key)) {
            throw new AfsBaseException("验证码已超时");
        }

        Object codeObj = redisTemplate.opsForValue().get(key);

        if (codeObj == null) {
            throw new AfsBaseException("验证码已超时");
        }

        String saveCode = codeObj.toString();
        if (StrUtil.isBlank(saveCode)) {
            redisTemplate.delete(key);
            throw new AfsBaseException("验证码错误");
        }

        if (!StrUtil.equals(saveCode, code)) {
            redisTemplate.delete(key);
            throw new AfsBaseException("验证码错误");
        }

        redisTemplate.delete(key);
    }
}
